using System.Linq;
using Amazon.ECS.Model;
using System;
using RomanJendrusz.Amazon.ETL.Infrastructure;
namespace RomanJendrusz.Amazon.ETL.Messages.MessageMappers
{
    public class GetOfferDetailsMapper: MessageMapper<GetOfferDetailsRequest, SellerListingLookupRequest, SellerListingLookupResponse>
    {
        private string exchangeId;
        public override AmazonResponse MapToAmazonResponse(SellerListingLookupResponse awsResponse)
        {
            var response = new GetOfferDetailsResponse(CorrelationId);
            response.ExchangeId = exchangeId;
            foreach (var listing in awsResponse.SellerListings)
            {
                var sellerListing = listing.SellerListing.SingleOrDefault(l => l.ExchangeId == exchangeId);
                if(sellerListing != null)
                {
                    response.EndDate = Convert.ToDateTime(AssertThat.IsNotNull(sellerListing.EndDate));
                    response.StartDate = Convert.ToDateTime(AssertThat.IsNotNull(sellerListing.StartDate));
                }
            }
            var minimumDate = new DateTime(1900,1,1);
            if(response.EndDate < minimumDate)
            {
                response.EndDate = minimumDate;
            }
            if(response.StartDate < minimumDate)
            {
                response.StartDate = minimumDate;
            }
            return response;
        }

        public override SellerListingLookupRequest MapToAwsRequest(GetOfferDetailsRequest request)
        {
            exchangeId = request.ExchangeId;
            var awsRequest = new SellerListingLookupRequest
                                 {
                                     SellerId = request.SellerId,
                                     Id = request.BookAsin,
                                     IdType = "ASIN"
                                 };
            awsRequest.ResponseGroup.Add(request.ResponseGroup);
            return awsRequest;
        }
    }
}